package QueueUse;/*
 *
 *@author:    Xavier
 *@data:      2023 - 08 - 18
 *@time:      15:27
 *
 */

import java.util.MissingFormatArgumentException;

//循环数组
//用数组实现队列
public class MyCircularQueue {
    private int[] elem;
    private int front;//队头下标
    private int rear;//队尾下标

    public MyCircularQueue(int val) {
        this.elem = new int[val];
    }

    //入队
    public boolean enQueue(int val) {
        if (isFull()) {
            return false;
        }
        elem[rear] = val;
        rear = (rear+1) % elem.length;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        front = (front+1) % elem.length;
        return true;
    }

    //得到队头元素
    public int Front(){
        if (isEmpty()) {
            return -1;
        }
        return elem[front];
    }

    //得到队尾元素
    public int Rear(){
        if (isEmpty()) {
            return -1;
        }
        int index = (rear == 0) ? elem.length-1 : rear -1;
        return elem[index];
    }

    public boolean isEmpty(){
        return rear == front;
    }

    //判断是否为满
    //两种方式
    //1、定义一个usedSize 当usedSize==len时 则满
    //2、浪费一个空间 当走到最后一个空间的前面一个的时候 则满
    public boolean isFull(){
        //这里采用的是第二中方法
        return (rear+1) % elem.length == front;
    }


    public static void main(String[] args) {
        MyCircularQueue myCircularQueue = new MyCircularQueue(3);
        myCircularQueue.enQueue(1);
        myCircularQueue.enQueue(2);
        myCircularQueue.enQueue(3);
        myCircularQueue.enQueue(4);
        myCircularQueue.enQueue(5);

        System.out.println(myCircularQueue.Rear());
        System.out.println(myCircularQueue.isFull());
        System.out.println(myCircularQueue.deQueue());
        System.out.println(myCircularQueue.enQueue(4));
        System.out.println(myCircularQueue.Rear());

    }






}


